<?php

namespace App\Http\Controllers\Frontend\V10\UnionLogin;

use App\Constant\FishCode;
use App\Constant\SmsTemplate;
use App\Facades\CommonPlatformRequestFacade;
use App\Http\Requests\Backend\AppUpdate\AppUpdateRequest;
use App\Http\Requests\Frontend\V10\Risk\RiskRequest;
use App\Library\Guzzle\Sign;
use App\Library\String\Aes;
use App\Library\String\UnionLoginTools;
use App\Models\SmallBlackFishPusher;
use App\Models\User;
use App\Rules\MobileCheck;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;
use App\Models\SourceErrRecords;
class FishController extends Controller {

    const ERR_TYPE_ONE = 1;//请求参数为空

    const ERR_TYPE_TWO = 2;//重复入库

    const ERR_TYPE_THREE = 3;//验签失败

    const ERR_TYPE_FOUR = 4;//业务逻辑异常

    const ERR_TYPE_FIVE = 5;//添加异常

    const SUCCESS_TYPE = 99;//成功
    //
    /**
     * 数据验证接口
     * @param Request $request
     * @return mixed
     * @author luwei
     * @date 2019-02-13 17:14
     */
    public function index(Request $request) {
        if (!$request->sign || !$request->phoneNo || !$request->timestamp) {
            return fishResp([], FishCode::MSG_PARAMS_NOT_FULL, FishCode::CODE_PARAMS_EMPTY);
        }
        try {
            $sign = $request->sign;
            $data = [
                'name'      => $request->name ?? '',
                'phoneNo'   => $request->phoneNo,
                'timestamp' => $request->timestamp,
            ];
            $flag = Sign::verify($data, $sign);
            if ($flag) {
                $phone = $request->phoneNo;
                $userModel = new User();
                $userModel->setConnection('backend');
                $user  = $userModel->where('phone_num_sha', $phone)->first();
                if ($user) {
                    $message = FishCode::MSG_IMPACT_SUCCESS_OLD;
                    $data    = [
                        'status' => FishCode::STATUS_OLD
                    ];
                } else {
                    $message = FishCode::MSG_IMPACT_SUCCESS_NEW;
                    $data    = [
                        'status' => FishCode::STATUS_NEW
                    ];
                }
                return fishResp($data, $message, FishCode::CODE_REQUEST_SUCCESS);
            } else {
                return fishResp([], FishCode::MSG_SIGN_ERROR, FishCode::CODE_SIGN_ERROR);
            }
        } catch (\Exception $e) {
            return fishResp([], $e->getMessage(), FishCode::CODE_OTHER_ERROR);
        }
    }


    /**
     * Description: 接收小黑鱼用户推送
     * Author: liuju
     * DateTime: 2019-02-14 13:23
     * @param Request $request
     * @return mixed
     */
    public function pusherInfo(Request $request) {
        $success = false;
        $code    = FishCode::CODE_OTHER_ERROR;
        $message = '系统其它异常';
        $status  = '0';
        try {
            //接受参数
            $paramsMap['name']      = $request->name;
            $paramsMap['orderNo']   = $request->orderNo;
            $paramsMap['phoneNo']   = $request->phoneNo;
            $paramsMap['timestamp'] = $request->timestamp;
            $paramsMap['sign']      = $request->sign;
            //$data = [];
            if(is_null($paramsMap['orderNo'])){
                unset($paramsMap['orderNo']);
            }
            foreach ($paramsMap as $key => $value) {
                if(!$value){
                    $code    = FishCode::CODE_PARAMS_EMPTY;
                    $message = '请求参数{'.$key.'}为空';
                    Log::debug("小黑鱼,请求参数{$key}为空请求参数：".json_encode($request->all(),JSON_UNESCAPED_UNICODE));
//                    return fishResp(['status' => $status], $message, $code, $success);
                }
            }

            $total = User::where('phone_num',$paramsMap['phoneNo'])->count();
            if($total>0){
                $code    = FishCode::CODE_REQUEST_SUCCESS;
                $success = true;
                $message = '成功';
                $status  = '1';
                SourceErrRecords::create([
                    'source'=>'41001',
                    'err_msg'=>"小黑鱼,重复入库",
                    'err_type'=>self::ERR_TYPE_TWO,
                    'phone_num'=> $paramsMap['phoneNo'],
                ]);
                Log::debug("小黑鱼,重复入库，请求参数：".json_encode($request->all(),JSON_UNESCAPED_UNICODE));
                return fishResp(['status' => $status], $message, $code, $success);
            }

            $sign = $paramsMap['sign'];
            unset($paramsMap['sign']);
            if (!Sign::verifyPush($paramsMap, $sign)) {
                $code    = FishCode::CODE_SIGN_ERROR;
                $message = '数据签名错误';
                SourceErrRecords::create([
                    'source'=>'41001',
                    'err_msg'=>"小黑鱼验签失败",
                    'err_type'=>self::ERR_TYPE_THREE,
                    'phone_num'=> $paramsMap['phoneNo'],
                ]);
                Log::debug("小黑鱼验签失败，请求参数：".json_encode($request->all(),JSON_UNESCAPED_UNICODE));
                return fishResp(['status' => $status], $message, $code, $success);
            }

            $paramsMap['orderNo'] = '';
            if (User::where('phone_num', $paramsMap['phoneNo'])->value('id')) {
                $code    = FishCode::CODE_LOGIC_ERROR;
                $message = '业务逻辑异常';
                SourceErrRecords::create([
                    'source'=>'41001',
                    'err_msg'=>"小黑鱼,业务逻辑异常",
                    'err_type'=>self::ERR_TYPE_FOUR,
                    'phone_num'=> $paramsMap['phoneNo'],
                ]);
                Log::debug("小黑鱼，业务逻辑异常，请求参数：".json_encode($request->all(),JSON_UNESCAPED_UNICODE));
                return fishResp(['status' => $status], $message, $code, $success);
            }

            $data = [
                'sign'=>$sign,
                'pusher_timestamp'=>$paramsMap['timestamp'],
                'order_num'=>$paramsMap['orderNo'],
                'phone_num'=>$paramsMap['phoneNo'],
            ];
            \DB::beginTransaction();
            SmallBlackFishPusher::create($data);

            //todo 填写渠道码
            $password = UnionLoginTools::randStr(6,'NUMBER');
            //需不需要调用User::createUser()这个函数
            User::createUser([
                'phone_num' => $paramsMap['phoneNo'],
                'password'  => $password,
                'source' => User::SOURCE_SMALL_BLACK_FISH,
            ]);
            //推送小黑鱼用户，快闪卡贷自动注册成功 todo 注册短信模板ID
            SmsTemplate::send(SmsTemplate::TEMPLATE_RZG_REGISTER, $paramsMap['phoneNo'], ['name' => $paramsMap['phoneNo'], 'password' => $password]);
            \DB::commit();
            $code    = FishCode::CODE_REQUEST_SUCCESS;
            $success = true;
            $message = '成功';
            $status  = '1';
            SourceErrRecords::create([
                'source'=>'41001',
                'err_msg'=>"添加成功",
                'err_type'=>self::SUCCESS_TYPE,
                'phone_num'=> $paramsMap['phoneNo'],
            ]);
            Log::debug("小黑鱼，添加成功，请求参数：".json_encode($request->all(),JSON_UNESCAPED_UNICODE));
            return fishResp(['status' => $status], $message, $code, $success);
        } catch (\Exception $e) {
            \DB::rollBack();
            SourceErrRecords::create([
                'source'=>'41001',
                'err_msg'=>"小黑鱼，添加异常",
                'err_type'=>self::ERR_TYPE_FIVE,
                'phone_num'=> $paramsMap['phoneNo'],
            ]);
            Log::debug("小黑鱼，添加异常，异常原因".$e->getMessage()."请求参数：".json_encode($request->all(),JSON_UNESCAPED_UNICODE));
            return fishResp(['status' => $status], $message, $code, $success);
        }

    }

    /**
     * Description: 接收小黑鱼用户推送
     * Author: liuju
     * DateTime: 2019-02-14 13:23
     * @param Request $request
     * @return mixed
     */
    public function pusherInfoForWeb(Request $request) {
        $success = false;
        $code    = FishCode::CODE_OTHER_ERROR;
        $message = '系统其它异常';
        $status  = '0';
        try {
            //接受参数
            $paramsMap['name']      = $request->name;
            $paramsMap['orderNo']   = $request->orderNo;
            $paramsMap['phoneNo']   = $request->phoneNo;
            $paramsMap['timestamp'] = $request->timestamp;
            $paramsMap['sign']      = $request->sign;
            //$data = [];
            if(is_null($paramsMap['orderNo'])){
                unset($paramsMap['orderNo']);
            }
            foreach ($paramsMap as $key => $value) {
                if(!$value){
                    $code    = FishCode::CODE_PARAMS_EMPTY;
                    $message = '请求参数{'.$key.'}为空';
                    Log::debug("小黑鱼web,请求参数{$key}为空请求参数：".json_encode($request->all(),JSON_UNESCAPED_UNICODE));
//                    return fishResp(['status' => $status], $message, $code, $success);
                }
            }

            $total = User::where('phone_num',$paramsMap['phoneNo'])->count();
            if($total>0){
                $code    = FishCode::CODE_REQUEST_SUCCESS;
                $success = true;
                $message = '成功';
                $status  = '1';
                Log::debug("小黑鱼web,重复入库，请求参数：".json_encode($request->all(),JSON_UNESCAPED_UNICODE));
                return fishResp(['status' => $status], $message, $code, $success);
            }

            $sign = $paramsMap['sign'];

            $paramsMap['orderNo'] = '';
            if (User::where('phone_num', $paramsMap['phoneNo'])->value('id')) {
                $code    = FishCode::CODE_LOGIC_ERROR;
                $message = '业务逻辑异常';
                Log::debug("小黑鱼web，业务逻辑异常，请求参数：".json_encode($request->all(),JSON_UNESCAPED_UNICODE));
                return fishResp(['status' => $status], $message, $code, $success);
            }

            $data = [
                'sign'=>$sign,
                'pusher_timestamp'=>$paramsMap['timestamp'],
                'order_num'=>$paramsMap['orderNo'],
                'phone_num'=>$paramsMap['phoneNo'],
            ];
            \DB::beginTransaction();
            SmallBlackFishPusher::create($data);

            //todo 填写渠道码
            $password = UnionLoginTools::randStr(6,'NUMBER');
            //需不需要调用User::createUser()这个函数
            User::createUser([
                'phone_num' => $paramsMap['phoneNo'],
                'password'  => $password,
                'source' => User::SOURCE_SMALL_BLACK_FISH,
            ]);
            //推送小黑鱼用户，快闪卡贷自动注册成功 todo 注册短信模板ID
            SmsTemplate::send(SmsTemplate::TEMPLATE_RZG_REGISTER, $paramsMap['phoneNo'], ['name' => $paramsMap['phoneNo'], 'password' => $password]);
            \DB::commit();
            $code    = FishCode::CODE_REQUEST_SUCCESS;
            $success = true;
            $message = '成功';
            $status  = '1';
            Log::debug("小黑鱼web，添加成功，请求参数：".json_encode($request->all(),JSON_UNESCAPED_UNICODE));
            return fishResp(['status' => $status], $message, $code, $success);
        } catch (\Exception $e) {
            \DB::rollBack();
            Log::debug("小黑鱼web，添加异常，异常原因".$e->getMessage()."请求参数：".json_encode($request->all(),JSON_UNESCAPED_UNICODE));
            return fishResp(['status' => $status], $message, $code, $success);
        }

    }


}


























